<?php
	class Imager{
		
		var $file;
		var $type;
		var $_imagep;
		
		function FromFile($file){
			$image = new Imager();
			$image->file=$file;
			
			$extmap=array(	"jpg"=>"jpg",
							"jpeg"=>"jpg",
							"gif"=>"gif",
							"png"=>"png");
			
			$names = explode(".",$file);
			$ext = strtolower(end($names));
			if(isset($extmap[$ext])) $ext = $extmap[$ext];
			$image->type=$ext;
			return $image;
		}
		
		
		function save($filename){
			$typeHandlers=array("jpg"=>"imagejpeg",
								"gif"=>"imagegif",
								"png"=>"imagepng");
								
			$typeHandlers[$this->type]($this->_imagep,$filename,100);
		}
		
		function constrainIn($width,$height=null){
			if(empty($height)) $height = $width;
			$this->_imagep = $this->_resize($width,$height,false);
			return $this->_imagep;
		}
		
		function scaleIn($width,$height=null){
			return $this->constrainIn($width,$height);
		}
		
		function fitIn(){
			
		}
		
		
		function raotate(){
			
		}		
		
		function _resize($width,$height=NULL,$isFit=true){
			
			if(isset($width) && isset($height)){
				$fixWidth=$width;
				$fixHeight=$height;
			}
			if($height==NULL) $height=$width;
			
			list($width_orig, $height_orig) = getimagesize($this->file);
	
			$ratio_orig = $width_orig/$height_orig;
			
			$srcX=0;
			$srcY=0;
			
			if ($width/$height > $ratio_orig) {
			   if($fixWidth>0 && $isFit){
			   		$ratio_orig = $height_orig/$width_orig;
			  		$width = $height*$ratio_orig;
			   		$oHeight=$height;
			   		$oHeight*=$width_orig/$fixWidth;
					$srcY=(($height_orig-$oHeight)/2);
					$height_orig -=($srcY * 2);
					$width=$fixWidth;
			   }else{
			   		$width=$width_orig*($height/$height_orig);
					
			   }
			   
			} else {
				
			   $height = $width/$ratio_orig;
			   if($fixHeight>0 && $isFit){
			   		$oWidth=$width;
			   		$oWidth*=$height_orig/$fixHeight;
					$srcX=(($width_orig-$oWidth)/2);
					$width_orig -=(($srcX * 2));
					
					$height=$fixHeight;
			   }else{
					$height=$height_orig*($width/$width_orig);
			   }
			}
			
			$image_p = imagecreatetruecolor($width, $height);
			
			$typeHandlers=array("jpg"=>"imagecreatefromjpeg",
								"gif"=>"imagecreatefromgif",
								"png"=>"imagecreatefrompng");
			
			$image = $typeHandlers[$this->type]($this->file);

			
			imagecopyresampled($image_p, $image, 0, 0, $srcX, $srcY, $width, $height, $width_orig, $height_orig);
			
			return $image_p;
		}
		
	}
?>